package com.sltx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.quantum.dubbo.core.utils.TextUtils;
import com.sltx.mapper.GainMapper;
import com.sltx.service.GainService;
import com.sltx.util.Conversion;
import com.sltx.util.ImportExcel;
import com.sltx.util.PageData;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import net.sf.json.JSONArray;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.math.BigDecimal;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author xue
 * @Date 2024/4/1 16:55
 */
@Service
public class GainServiceImpl implements GainService {

    @Autowired
    private GainMapper gainMapper;

    //获取出去存储到数据库-地方标准 730
    @Override
    public Object getHuoqu(PageData pd) throws Exception {
        StringBuilder response = null;
        Integer pages = 377;
        for (Integer i = 1; i <= pages; i++) {
            // 创建URL对象
            URL url = new URL("https://dbba.sacinfo.org.cn/stdQueryList?");
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 设置请求头部信息
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "UTF-8");
            // 设置请求体参数
            String parameters = "current=" + i + "&size=" + pd.get("size") + "&key=&ministry=&industry=&pubdate=&date=&status=" + pd.get("status");
            // 6. 获取输出流
            connection.setDoOutput(true);
            // 获取输出流并写入请求数据
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(parameters.getBytes("UTF-8"));
            outputStream.flush();
            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            // 读取响应数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            String shuju = response.toString();
            JSONObject jsonObject = JSONObject.parseObject(shuju);
            //获取多少页
            List<Map<String, Object>> records = (List<Map<String, Object>>) jsonObject.get("records");
            reader.close();
            // 关闭连接
            connection.disconnect();
            for (int i1 = 0; i1 < records.size(); i1++) {
                //将数据存储数据库中
                gainMapper.insteShuju(records.get(i1));
            }
            Thread.sleep(3000L);
        }

        return "OK";
    }

    //获取数据存储到数据库-行业标准信息服务平台 2024-8-20 获取近半年的
    @Override
    public Object Hangye(PageData pd) throws Exception {
        StringBuilder response = null;
        Integer pages = 22;
        for (Integer i = 1; i <= pages; i++) {
            // 创建URL对象
            URL url = new URL("https://hbba.sacinfo.org.cn/stdQueryList?");
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 设置请求头部信息
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "UTF-8");
            // 设置请求体参数
            String parameters = "current=" + i + "&size=" + pd.get("size") + "&key=&ministry=&industry=&pubdate=&date=&status=" + pd.get("status");
            // 6. 获取输出流
            connection.setDoOutput(true);
            // 获取输出流并写入请求数据
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(parameters.getBytes("UTF-8"));
            outputStream.flush();
            // 读取响应数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            String shuju = response.toString();
            JSONObject jsonObject = JSONObject.parseObject(shuju);
            //获取多少页
            List<Map<String, Object>> records = (List<Map<String, Object>>) jsonObject.get("records");
            reader.close();
            // 关闭连接
            connection.disconnect();
            for (int i1 = 0; i1 < records.size(); i1++) {
                //将数据存储数据库中-行业标准信息服务平台
                gainMapper.insteIndustry(records.get(i1));
            }
            Thread.sleep(5000L);
        }

        return "OK";
    }

    //获取数据存储到数据库-国家标准目录查询 1381
    @Override
    public Object State(PageData pd) throws Exception {
        Integer pages = 12;
        JSONObject jsonObject = null;
        for (Integer i = 1; i <= pages; i++) {
            //创建信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };
            // 初始化SSLContext并设置TrustManager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            // 设置主机名验证器（如果需要）
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
            String apiUrl = "https://std.samr.gov.cn/gb/search/gbQueryPage";
            String asc = "asc";
            String pageSize = "50";
            String pageNumber = i.toString();
            try {
                URL url = new URL(apiUrl + "?sortOrder=" + asc + "&pageSize=" + pageSize + "&pageNumber=" + pageNumber);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                jsonObject = JSONObject.parseObject(response.toString());
                List<Map<String, Object>> rows = (List<Map<String, Object>>) jsonObject.get("rows");
                for (int i1 = 0; i1 < rows.size(); i1++) {
                    //将国家数据存储到数据库
                    gainMapper.insteShujuState(rows.get(i1));
                }
                Thread.sleep(3000L);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    //查询地方标准信息平台pk
    @Override
    public Object dfkey(PageData pd) {
        //获取当前页((当前页-1)*每页个数)
        Integer PageNo = (Integer.parseInt(pd.get("PageNo").toString()) - 1) * Integer.parseInt(pd.get("PageSize").toString());
        //获取每页个数
        Integer PageSize = Integer.parseInt(pd.get("PageSize").toString());
        pd.put("PageNo", PageNo);//当前页
        pd.put("PageSize", PageSize);//每页个数
        //查询地方标准信息平台pk
        List<Map<String, Object>> pk = gainMapper.getPKdf(pd);
        return pk;
    }

    //查询行业标准信息平台pk
    @Override
    public Object hypk(PageData pd) {
        //获取当前页((当前页-1)*每页个数)
        Integer PageNo = (Integer.parseInt(pd.get("PageNo").toString()) - 1) * Integer.parseInt(pd.get("PageSize").toString());
        //获取每页个数
        Integer PageSize = Integer.parseInt(pd.get("PageSize").toString());
        pd.put("PageNo", PageNo);//当前页
        pd.put("PageSize", PageSize);//每页个数
        //查询地方标准信息平台pk
        List<Map<String, Object>> pk = gainMapper.getPKhy(pd);
        return pk;
    }

    //查询国家标准目录id
    @Override
    public Object stateid(PageData pd) {
        //获取当前页((当前页-1)*每页个数)
        Integer PageNo = (Integer.parseInt(pd.get("PageNo").toString()) - 1) * Integer.parseInt(pd.get("PageSize").toString());
        //获取每页个数
        Integer PageSize = Integer.parseInt(pd.get("PageSize").toString());
        pd.put("PageNo", PageNo);//当前页
        pd.put("PageSize", PageSize);//每页个数
        //查询地方标准信息平台pk
        List<Map<String, Object>> stateid = gainMapper.getStateid(pd);
        return stateid;
    }

    //读取文件获取文件名
    @Override
    public Object excelread(PageData pd, MultipartFile file) {
        List<Map<String, Object>> list = null;
        try {
            //获取上传的文件名
            String fileName = file.getOriginalFilename();
            // 获取上传文件的输入流
            InputStream inputStream = file.getInputStream();
            // 调用工具类中方法，读取excel文件中数据
            list = ImportExcel.readExcel(fileName, inputStream);
            for (int i = 0; i < list.size(); i++) {
                //获取标准名称
                String chName = list.get(i).get("chName").toString();
                //获取中国号
                String chinanumber = list.get(i).get("china_number").toString();
                //获取国际号
                String issn = list.get(i).get("issn").toString();
                //获取企业名称
                String entname = list.get(i).get("entname").toString();
                pd.put("chName", chName);
                pd.put("chinanumber", chinanumber);
                pd.put("issn", issn);
                pd.put("entname", entname);
                //插入三个字段数据
                gainMapper.update(pd);

            }
        } catch (Exception e) {
            return e;
        }
        return list;
    }

    @Override
    public Object updateEntname(PageData pd) {
        //获取数据
        List<String> entnames = gainMapper.getEntname();
        for (int i = 0; i < entnames.size(); i++) {
            String[] split = entnames.get(i).split("、");
            String s = split[0];
            if (s.length() < 4 && s.length() > 1) {
                //删除这条数据
                String s1 = Arrays.toString(split).replace("[", "").replace("]", "");
                String replace1 = s1.replace(", ", "、");
                pd.put("entname", replace1);
                gainMapper.updateEntname(pd);
            }
        }
        return "OK";
    }

    //替换issn含有中文为''
    @Override
    public Object updatezwbm(PageData pd) {
        //获取所有的issn
        List<String> issns = gainMapper.getZgbm();
        Pattern compile = Pattern.compile("[\u4e00-\u9fa5]");
        for (int i = 0; i < issns.size(); i++) {
            String s = issns.get(i);
            Matcher matcher = compile.matcher(s);
            if (matcher.find()) {
                pd.put("issn", s);
                gainMapper.updateissn(pd);
            }
        }
        return "OK";
    }

    //替换行业中china_number字段中含有中文为''
    @Override
    public Object updatezgxh(PageData pd) {
        List<String> chinanumbers = gainMapper.getchinanumber();
        Pattern compile = Pattern.compile("[\u4e00-\u9fa5]");
        for (int i = 0; i < chinanumbers.size(); i++) {
            String s = chinanumbers.get(i);
            Matcher matcher = compile.matcher(s);
            if (matcher.find()) {
                pd.put("chinanumber", s);
                gainMapper.updatechinanumber(pd);
            }
        }
        return "OK";
    }

    //删除国家表中entname字段里面的无用数据
    @Override
    public Object updateState(PageData pd) {
        //获取entname和id字段
        List<Map<String, Object>> mapList = gainMapper.getEntnameId();
        Pattern pattern = Pattern.compile("[0-9]");
        for (int i = 0; i < mapList.size(); i++) {
            String entname = mapList.get(i).get("entname").toString();
            try {
                if (!entname.isEmpty()) {
                    if (pattern.matcher(entname).find()) {//如果里面包含数字
                        int a = 0;
                        String[] split = entname.split(",");
                        for (int i1 = 0; i1 < split.length; i1++) {
                            if (pattern.matcher(split[i1]).find()) { //如果包含数字
                                a = i1;
                            }
                        }
                        ArrayList<String> list1 = new ArrayList<>(Arrays.asList(split));
                        list1.subList(0, a + 1).clear();
                        String replace = list1.toString().replace("[", "").replace("]", "");
                        String id = mapList.get(i).get("id").toString();//获取此数据的id
                        pd.put("id", id);
                        pd.put("entname", replace);
                        //根据此id更换entname
                        gainMapper.updateEntnameState(pd);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return 1;
    }

    //拆分shuju_bz中entname字段并存入数据库多条
    @Override
    public Object updateentname(PageData pd) {
        List<Map<String, Object>> list = gainMapper.getbzEntname(pd);
        for (int i = 0; i < list.size(); i++) {
            String[] entnames = list.get(i).get("entname").toString().split(",");
            for (int i1 = 0; i1 < entnames.length; i1++) {
                pd.put("entname", entnames[i1]);
                pd.put("C_STD_CODE", list.get(i).get("C_STD_CODE"));
                pd.put("C_C_NAME", list.get(i).get("C_C_NAME"));
                pd.put("ACT_DATE", list.get(i).get("ACT_DATE"));
                pd.put("STATE", list.get(i).get("STATE"));
                pd.put("ISSUE_DATE", list.get(i).get("ISSUE_DATE"));
                pd.put("built_date", list.get(i).get("built_date"));
                pd.put("china_number", list.get(i).get("china_number"));
                pd.put("issn", list.get(i).get("issn"));
                gainMapper.instebzEntname(pd);
            }
        }
        return "OK";
    }

    //拆分entname并存入数据库多条-地方标准信息服务平台
    @Override
    public Object updateentnameplace(PageData pd) {
        //查询所有数据-地方标准信息服务平台
        gainMapper.update2();
        List<Map<String, Object>> list = gainMapper.getPlaceEntname(pd);
        for (int i = 0; i < list.size(); i++) {
            String[] entnames = list.get(i).get("entname").toString().split("[，、。,\\.\\s&\\\\]+");
            for (int i1 = 0; i1 < entnames.length; i1++) {
                pd.put("entname", entnames[i1]);
                pd.put("code", list.get(i).get("code"));
                pd.put("industry", list.get(i).get("industry"));
                pd.put("chname", list.get(i).get("chname"));
                pd.put("pk", list.get(i).get("pk"));
                pd.put("status", list.get(i).get("status"));
                pd.put("recordno", list.get(i).get("recordno"));
                pd.put("built_date", list.get(i).get("built_date"));
                pd.put("china_number", list.get(i).get("china_number"));
                pd.put("issn", list.get(i).get("issn"));
                pd.put("recorddate", list.get(i).get("recorddate"));
                pd.put("issuedate", list.get(i).get("issuedate"));
                pd.put("actdate", list.get(i).get("actdate"));
                //将地方拆分完的数据存到数据库表-shuju-cf
                gainMapper.instePlaceEntname(pd);
            }
        }
        return "OK";
    }

    //拆分entname并存入数据库多条-行业标准信息服务平台
    @Override
    public Object updateentnameindustry(PageData pd) {
        gainMapper.update3();
        //查询所有数据-行业标准信息服务平台
        List<Map<String, Object>> list = gainMapper.getEntnameindustry(pd);
        for (int i = 0; i < list.size(); i++) {
            String[] entnames = list.get(i).get("entname").toString().split("[，、。：,＆;\\.\\s&\\\\]+");
            for (int i1 = 0; i1 < entnames.length; i1++) {
                if (entnames[i1].endsWith("等")) {
                    String entname = entnames[i1].substring(0, entnames[i1].length() - 1);
                    pd.put("entname", entname);
                } else {
                    pd.put("entname", entnames[i1]);
                }
                pd.put("code", list.get(i).get("code"));
                pd.put("industry", list.get(i).get("industry"));
                pd.put("chname", list.get(i).get("chname"));
                pd.put("pk", list.get(i).get("pk"));
                pd.put("status", list.get(i).get("status"));
                pd.put("recordno", list.get(i).get("recordno"));
                pd.put("built_date", list.get(i).get("built_date"));
                pd.put("china_number", list.get(i).get("china_number"));
                pd.put("issn", list.get(i).get("issn"));
                pd.put("recorddate", list.get(i).get("recorddate"));
                pd.put("issuedate", list.get(i).get("issuedate"));
                pd.put("actdate", list.get(i).get("actdate"));
                //将地方拆分完的数据存到数据库表-shuju_industry_cf
                gainMapper.insteIndustryEntname(pd);
            }

        }
        return "OK";
    }

    //拆分entname并存入数据库多条-全国标准信息公共服务平台
    @Override
    public Object updateentnamestate(PageData pd) {

        gainMapper.update4();
        //查询所有数据-全国标准信息公共服务平台
        List<Map<String, Object>> list = gainMapper.getEntnamestate(pd);
        for (int i = 0; i < list.size(); i++) {
            String[] entnames = list.get(i).get("entname").toString().split("[、,＆;\\.\\s&\\\\]+");
            for (int i1 = 0; i1 < entnames.length; i1++) {
                pd.put("entname", entnames[i1]);
                pd.put("C_STD_CODE", list.get(i).get("C_STD_CODE"));
                pd.put("C_C_NAME", list.get(i).get("C_C_NAME"));
                pd.put("ACT_DATE", list.get(i).get("ACT_DATE"));
                pd.put("STATE", list.get(i).get("STATE"));
                pd.put("ISSUE_DATE", list.get(i).get("ISSUE_DATE"));
                pd.put("built_date", list.get(i).get("built_date"));
                pd.put("china_number", list.get(i).get("china_number"));
                pd.put("issn", list.get(i).get("issn"));
                //将地方拆分完的数据存到数据库表-shuju_state_cf
                gainMapper.insteStateEntname(pd);
            }
        }
        return "OK";
    }

    //将标准信息存入数据库
    @Override
    public Object instStandardsInfo(PageData pd) {
        //查询需要推送的企业有多少条
        Integer num = gainMapper.getNum();
        try {
            for (Integer i = 1; i <= num; i++) {
                String entname = null;
                //查询一个统一社会信用代码
                entname = gainMapper.getUniscid();
                if (entname == null) {
                    //查询一个企业名
                    entname = gainMapper.getEntnameZxc();
                }
                pd.put("entName", Conversion.codeConversion(entname));
                pd.put("level", Conversion.codeConversion(pd.get("level").toString()));
                pd.put("pageSize", Conversion.codeConversion(pd.get("pageSize").toString()));
                pd.put("pageNo", Conversion.codeConversion(pd.get("pageNo").toString()));
                net.sf.json.JSONObject jo = Conversion.getServiceData("getStandardsInfo", pd);
                Map<String, Object> pageinfo = (Map<String, Object>) jo.get("PAGEINFO");//获取有多少页数据
                if (pageinfo == null) {
                    //如果没有数据就更换这个企业sfcx为2
                    gainMapper.updateEntnamesfcx(entname);
                    this.instStandardsInfo(pd);
                }
                Integer page = (Integer) pageinfo.get("TOTAL_PAGE");//一共有多少页
                for (int a = 1; a <= page; a++) {
                    pd.put("pageNo", Conversion.codeConversion(Integer.toString(a)));
                    net.sf.json.JSONObject jo1 = Conversion.getServiceData("getStandardsInfo", pd);
                    List<Map<String, Object>> list = jo1.getJSONArray("RESULTDATA");
                    for (Map<String, Object> stringObjectMap : list) {
                        //将数据存储到数据库中
                        gainMapper.instStandardsInfo(stringObjectMap);
                    }
                }
                System.out.println("已推送=====>" + i + "家，当前推送的企业名为======>" + entname);
                //推送完此企业将状态改为1
                gainMapper.updateEntnameZxc(entname);
                Random random = new Random();
                int millisecond = random.nextInt(5000);
                System.out.println("睡眠=====>" + millisecond + "毫秒");
                Thread.sleep(millisecond);
            }
        } catch (Exception e) {
            this.instStandardsInfo(pd);
        }
        return "ok";
    }

    //拆分团体数据的企业字段
    @Override
    public Object updatetuanti() {
        Map<String, Object> pd = new HashMap<>();
        //查询所有数据-团体数据
        gainMapper.update1();
        List<Map<String, Object>> list = gainMapper.getEntnametuanti();
        for (int i = 0; i < list.size(); i++) {
            String[] entnames = list.get(i).get("draftunit").toString().split("[、。，；＆;]");
            for (int i1 = 0; i1 < entnames.length; i1++) {
                pd.put("draftunit", entnames[i1]);
                pd.put("code", list.get(i).get("code"));
                pd.put("chname", list.get(i).get("chname"));
                pd.put("status", list.get(i).get("status"));
                pd.put("issuedate", list.get(i).get("issuedate"));
                pd.put("actdate", list.get(i).get("actdate"));
                int i2 = list.get(i).get("ics").toString().lastIndexOf(" ");
                if (i2 != -1) {
                    pd.put("ics", list.get(i).get("ics").toString().substring(0, i2));
                } else {
                    pd.put("ics", list.get(i).get("ics").toString());
                }
                pd.put("ccs", list.get(i).get("ccs"));
                //将地方拆分完的数据存到数据库表-shuju_tuanti_cf
                gainMapper.instEntnametuanti(pd);
            }
        }
        return "OK";
    }


}










